package cn.hpclub.server.controller.admin;

import java.io.UnsupportedEncodingException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.concurrent.ConcurrentHashMap;

import cn.hpclub.server.service.TariffService;
import com.jfinal.ext.render.excel.PoiRender;
import com.jfinal.plugin.activerecord.Record;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.jfinal.aop.Before;
import com.jfinal.kit.StrKit;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.tx.Tx;

import cn.hpclub.server.model.Broadband;
import cn.hpclub.server.service.BroadbandService;
import cn.hpclub.server.util.InterfaceUtil;
import cn.hpclub.server.util.ResultCode;
import cn.hpclub.server.validator.admin.BroadbandValidator;

public class BroadbandController extends BaseAdminController<Broadband>{
    private static final Logger logger = LoggerFactory.getLogger(BroadbandController.class);
    // private Broadband broadband;

    @SuppressWarnings("static-access")
    public void list(){
        ConcurrentHashMap<String, String> searchInfo = getSearchInfo();
        String select = "select u.user_name,j.DisplayName org_name,b.*";
        findByPageForSearch(select, new BroadbandService().service.getSqlExceptSelect(searchInfo));
        setAttrs(searchInfo);
        render("/admin/broadband_list.tpl");
    }

    public void export(){
        ConcurrentHashMap<String, String> searchInfo = getSearchInfo();
        List<Record> list = BroadbandService.service.export(searchInfo);

        PoiRender excel = PoiRender.me(list);
        String[] headesExport = BroadbandService.headesExport;
        String[] columnsExport = BroadbandService.columnsExport;

        render(excel.sheetName("宽带套餐配置").headers(headesExport).columns(columnsExport).fileName(generateFileName()));
    }

    private String generateFileName(){
        Date date = new Date();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd-HH-mm-ss");
        String curTime = sdf.format(date);
        String fileName = "宽带套餐配置-" + curTime + ".xlsx";
        // System.out.println("excel file name:" + fileName);
        try {
            return new String(fileName.getBytes("gbk"),"iso8859-1");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return fileName;
    }

    public void delete(){

        String[] ids = getParaValues("ids");
        logger.debug("broadband delete ids.len:" + ids.length);

        /*
         * 由于唯一性问题先屏蔽掉：String[] codes =
         * BroadbandService.service.findCodesByIds(ids);
         * BusinessService.service.deleteByCodes(codes);
         */

        ResultCode result = BroadbandService.service.delete(ids);

        if(result == ResultCode.SUCCESS){
            ajaxJsonSuccessMessage("删除成功");
        } else if(result == ResultCode.PARAM_ERROR){
            ajaxJsonErrorMessage("删除失败");
        } else if(result == ResultCode.FAILED){
            ajaxJsonErrorMessage("删除失败");
        }
    }

    /*
     * 编辑
     */
    public void edit(){
        String id = getPara("broadband.id", "");
        logger.info("id=" + id);
        if(StrKit.notBlank(id)){
            Broadband broadband = Broadband.dao.findById(id);
            setAttr("broadband", broadband);

            /*
             * 由于唯一性问题先屏蔽掉：Integer businessId =
             * BusinessService.service.findBusinessByCode(broadband.getStr(
             * Broadband.BUSINESS_CODE)).getInt(Business.ID);
             * setAttr("businessId", businessId);
             */
        }
        render("/admin/broadband_add.tpl");
    }

    private Broadband modalBind(boolean isAdd){
        Broadband modal = new Broadband();
        Integer id = getParaToInt("broadband.id", null);
        String name = getPara("broadband.name", "");// 业务名称
        String business_summary = getPara("broadband.business_summary", "");// 业务简介
        String introduction = getPara("broadband.introduction", "");// 业务介绍
        String city = getPara("broadband.city", "");// 城市
        String price = getPara("broadband.price", "0");// 价格
        String period = getPara("broadband.period", "");// 计费周期
        String width = getPara("broadband.width", "");// 带宽
        String broad_type = getPara("broadband.broad_type", "");// 宽带商家类型
        String brand = getPara("broadband.brand", "");// 宽带品牌
        int member_phone_count = getParaToInt("broadband.member_phone_count", 0);// 成员手机号的数量
        String first_install_cost = getPara("broadband.first_install_cost", "0.00");// 初装费
        String business_code = getPara("broadband.business_code", "");// 资费代码

        // 适用范围，1为开户，2为预约，3为开户和预约。如果没有，默认为预约类型。
        int open = getParaToInt("apply_open", 0);
        int reserve = getParaToInt("apply_reserve", 0);
        int temp = open + reserve;
        int businessType = ((temp == 0) ? 2 : temp);

        System.out.println("check1:" + open);
        System.out.println("check2:" + reserve);
        String order_num = getPara("broadband.order_num", "");// 排序数字
        modal.set("id", id).set("name", name).set("business_summary", business_summary)
                .set("introduction", introduction).set("city", city).set("price", price).set("period", period)
                .set("width", width).set("broad_type", broad_type).set("brand", brand)
                .set("member_phone_count", member_phone_count).set("first_install_cost", first_install_cost)
                .set("business_code", business_code).set("order_num", order_num).set("business_type", businessType);
        Date now = new Date();
        if(isAdd){
            int org_id = InterfaceUtil.getOrgId();// 当前用户机构id
            int creator = InterfaceUtil.getAdminId();// 当前用户id
            modal.set("create_time", now).set("org_id", org_id).set("creator", creator).set("enabled", 0);
        }
        return modal;
    }

    /*
     * 新增
     */
    @Before({ Tx.class, BroadbandValidator.class })
    public void save(){
        Broadband broadband = modalBind(true);
        broadband.save();

        // 同时新增business
        /*
         * 由于唯一性问题先屏蔽掉：BusinessService.service.saveBusinessByCodeAndName(
         * broadband.getStr(Broadband.BUSINESS_CODE),
         * broadband.getStr(Broadband.NAME)); redirect("/broadband/list");
         */
        redirect("/broadband/list");
    }

    public void add(){
        setAttr("broadband", new Broadband());
        render("/admin/broadband_add.tpl");
    }

    /*
     * 修改
     */
    @Before({ Tx.class, BroadbandValidator.class })
    public void update(){
        Broadband broadband = modalBind(false);
        broadband.update();

        // 同时修改business的
        /*
         * 由于唯一性问题先屏蔽掉：BusinessService.service.updateCodeAndName(broadband.
         * getStr(Broadband.BUSINESS_CODE), broadband.getStr(Broadband.NAME),
         * getPara("businessId"));
         */
        redirect("/broadband/list");
    }

    public void enable(){
        enableBraodband(1, "启用");
    }

    public void disable(){
        enableBraodband(0, "禁用");
    }

    private void enableBraodband(int enabled, String actionName){
        logger.info("enabled=" + enabled);
        String[] ids = getParaValues("ids");

        StringBuffer sb = new StringBuffer();
        sb.append("UPDATE broadband SET enabled = " + enabled + " WHERE id IN (");
        if(ids.length > 0){
            for(int i = 0; i < ids.length; i++){
                if(i == ids.length - 1){
                    sb.append("?");
                } else{
                    sb.append("?,");
                }
            }
            sb.append(")");
        } else{
            ajaxJsonErrorMessage(actionName + "失败");
            return;
        }
        boolean success = Db.update(sb.toString(), (Object[])ids) > 0;
        if(success){
            ajaxJsonSuccessMessage(actionName + "成功");
        } else{
            ajaxJsonErrorMessage(actionName + "失败");
        }
    }

}
